package com.julang.check.controller;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.julang.check.bean.RequestEntity;
import com.julang.check.bean.ResponseEntity;
import com.julang.check.bean.User;
import com.julang.check.annotation.NotNeedToken;
import com.julang.check.api.mapper.UserMapper;
import com.julang.check.service.TokenService;
import com.julang.check.utils.CommonData;
import com.julang.check.utils.Result;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.julang.check.utils.CommonData.*;
import static com.julang.check.utils.MessageInfo.*;
/**
 * @author 赵自强
 * */
@RestController
@RequestMapping(value = "/api/user")
@Api(tags = "用户操作")
public class UserController extends BaseController{

    @Resource
    UserMapper mapper;
    @Autowired
    TokenService tokenService;

    @PostMapping(value = "/register")
    @ResponseBody
    @NotNeedToken
    @ApiOperation("用户注册")
    public Result<User> addUser(@RequestBody @ApiParam(value = "用户信息",required = true) @ModelAttribute RequestEntity.RegisterBody user){
        System.out.println("route: /api/user");
        System.out.println(user.toString());
        User ue = new User(user);
        int i = mapper.insert(ue);
        Result<User> result = new Result<User>();
        if (i == ONEOFNUMBER) {
            result.success("注册成功", ue);
        }else {
            result.fail(DATABASEERROR,"注册成功", ue);
        }
        return result;
    }

    @PostMapping(value = "/login")
    @ResponseBody
    @NotNeedToken
    @ApiOperation("用户登录")
    public Result<ResponseEntity.LoginResponse> login(@RequestBody RequestEntity.LoginBody request) {
        System.out.println(request.toString());
        User user1 = mapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getEmail, request.getUserName()));
        if (user1 == null) {
            return Result.buildError(USERNOTLOGINCODE, "帐号不存在", null);
        }
        if (!request.getPassword().equals(user1.getPassword())) {
            return Result.buildError(PASSWORDERRORCODE, "密码错误", null);
        }
        ResponseEntity.LoginResponse response = new ResponseEntity.LoginResponse();
        response.setNickname(user1.getUsername());
        response.setJifen(user1.getJifen());
        response.setToken(tokenService.getToken(user1));
        return Result.buildSuccess("登录成功", response);
    }
    @PostMapping(value = "/oauth")
    @ResponseBody
    @ApiOperation("重新获取jwt token")
    @ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
    public Result<String> oauth(@RequestBody String token){
        String userId = JWT.decode(token).getAudience().get(0);
        System.out.println("刷新的id: " + userId);
        User user = mapper.selectById(userId);
        Result<String> result = new Result<String>();
        result.success("刷新Token成功", tokenService.getToken(user));
        return result;
    }

    @GetMapping(value = "/user_info")
    @ResponseBody
    @ApiOperation("获取用户信息")
    @ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
    public Result<User> getUserInfo(HttpServletRequest request) {
        String userId = this.getUserId();
        User user = mapper.selectById(userId);
        Result<User> result = new Result<User>();
        if (user == null) {
            result.fail(USERNOTLOGINCODE, "帐号不存在", null);
        }else {
            user.setPassword("");
            result.success("", user);
        }
        return result;
    }

    @RequestMapping(value = "/modify_password", method = {RequestMethod.POST})
    @ResponseBody
    @ApiOperation("修改用户密码")
    @ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
    public Result<String> queryOrder(HttpServletRequest request,@RequestBody RequestEntity.ModifyPwdBody params) {
        String oldPassword = params.getOldpassword();
        String password = params.getPassword();
        if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(password) ) {
            return Result.buildError(CommonData.FAIL, BLANKPOSTPARAM, "");
        }
        String userId = this.getUserId();
        User user = mapper.selectById(userId);
        if (user == null) {
            return Result.buildError(CommonData.FAIL, USERNOTEXIST, "");
        }
        if (!user.getPassword().equals(oldPassword)) {
            return Result.buildError(CommonData.FAIL, OLDPWDNOTRIGHT, "");
        }
        user.setPassword(password);
        mapper.updateById(user);
        return Result.buildSuccess();
    }
}
